/* 
 Created on : 2014-7-13
 Author     : MLeo
 */
(function($) {
    $.fn.pagination = function(options) {
        var _obj = $(this); //对象
        var settings = $.extend({"_obj": _obj}, $.fn.pagination.defaults, options); //合并参数
        paginationLoad(settings); //分页标签的加载

        paginationAjax(settings); //数据的获取

        paginationBind(settings);//绑定事件

        return this;
    };
    /**
     * 初始化分页插件
     * @param {type} settings
     * @returns {undefined}
     */
    var paginationLoad = function(settings) {
        var paginationLoad = settings._obj.data("paginationLoad");
        if (!paginationLoad) {
            settings._obj.data("paginationLoad", true);
            var pagination_html = "";
            pagination_html += "<div class =\"pagination_class\" style = \"display: none;\">";
            pagination_html += "<span id = \"_home\">首页</span>";
            pagination_html += "<span id = \"_previous\" >上一页</span>";
            pagination_html += "<span id = \"_next\" >下一页</span>";
            pagination_html += "<span id = \"_end\">末页</span>";
            pagination_html += "<span> 每页<select id = \"_page_size\"><option value = \"1\">1</option><option value = \"5\">5</option><option value = \"10\">10</option><option value = \"20\">20</option></select>条</span>";
            pagination_html += "<span> 第 <input type = \"number\" id = \"_current_page\" /> / <span id = \"_totalPage\">1</span> 页</span>";
            pagination_html += "</div>";
            settings._obj.append(pagination_html);
            settings._obj.find("#_page_size").find("option[value = '" + settings.pageSize + "']").prop("selected", true);
            settings._obj.find("#_current_page").val(settings.currentPage);
        } else {
            settings._obj.find("#_current_page").val(settings.currentPage);
        }
    };
    /**
     * 加载数据信息
     * @param {type} settings
     * @returns {undefined}
     */
    var paginationAjax = function(settings) {

        var pageSize = settings._obj.find("#_page_size").val();
        var currentPage = settings._obj.find("#_current_page").val();
        var param = settings.param;
        if (param) {
            if ('object' === typeof (param)) {
                param = $.extend({}, settings.param, {"pageSize": pageSize, "currentPage": currentPage}); //合并参数
            } else {
                param = param + "&" + $.param({"pageSize": pageSize, "currentPage": currentPage}); //合并参数
            }
        } else {
            param = {"pageSize": pageSize, "currentPage": currentPage};
        }
        if (settings.url) {
            $.ajax({
                url: settings.url,
                async: settings.async,
                type: settings.type,
                data: param,
                dataType: settings.dataType,
                success: function(result, textStatus, jqXHR) {
                    var data = null;
                    if (settings.bean) {
                        data = result[settings.bean];
                    } else {
                        data = result;
                    }
                    if (data) {
                        if (data.dataCount) {
                            var count = Math.ceil(data.dataCount / data.pageSize);
                            var currentPage = data.currentPage;
                            settings._obj.find("#_totalPage").text(count);

                            if (currentPage === 1 && currentPage < count) {
                                settings._obj.find("#_home").hide();
                                settings._obj.find("#_previous").hide();
                                settings._obj.find("#_next").show();
                                settings._obj.find("#_end").show();
                            } else if (currentPage > 1 && currentPage < count) {
                                settings._obj.find("#_home").show();
                                settings._obj.find("#_previous").show();
                                settings._obj.find("#_next").show();
                                settings._obj.find("#_end").show();
                            } else if (currentPage > 1 && currentPage === count) {
                                settings._obj.find("#_home").show();
                                settings._obj.find("#_previous").show();
                                settings._obj.find("#_next").hide();
                                settings._obj.find("#_end").hide();
                            } else {
                                settings._obj.find("#_home").hide();
                                settings._obj.find("#_previous").hide();
                                settings._obj.find("#_next").hide();
                                settings._obj.find("#_end").hide();
                            }
                        } else {
                            settings._obj.find("#_home").hide();
                            settings._obj.find("#_previous").hide();
                            settings._obj.find("#_next").hide();
                            settings._obj.find("#_end").hide();
                        }
                        settings._obj.find(".pagination_class").show();
                        if (data.list) {
                            if (settings.success) {
                                settings.success(result, textStatus, jqXHR);
                            }
                            if (settings.achieve) {
                                paginationAchieve(settings, data.list);
                            }
                        }
                    } else {
                        return;
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    if (settings.error) {
                        settings.error(XMLHttpRequest, textStatus, errorThrown);
                    }
                }
            });
        }
    };
    /**
     * 绑定分页事件
     * @param {type} settings
     * @returns {undefined}
     */
    var paginationBind = function(settings) {
        settings._obj.off();
        settings._obj.on("click", "span[id ^= \"_\"]", function() {
            var span_id = $(this).attr("id");
            var current_value = settings._obj.find("#_current_page").val();
            var max_current_value = settings._obj.find("#_totalPage").first().text();
            if ("_home" === span_id) {
                settings._obj.find("#_current_page").val(1);
            } else if ("_previous" === span_id) {
                settings._obj.find("#_current_page").val(eval(current_value + "-1") < 1 ? 1 : eval(current_value + "-1"));
            } else if ("_next" === span_id) {
                settings._obj.find("#_current_page").val(eval(current_value + "+1") > max_current_value ? max_current_value : eval(current_value + "+1"));
            } else if ("_end" === span_id) {
                settings._obj.find("#_current_page").val(max_current_value);
            }
            paginationAjax(settings);
        });
        settings._obj.on("change", "select", function() {
            settings._obj.find("#_page_size").find("option[value = '" + $(this).val() + "']").prop("selected", true);
            settings._obj.find("#_current_page").val(1);
            paginationAjax(settings);
        });
        settings._obj.on("change", "input", function() {
            var max_current_value = settings._obj.find("#_totalPage").first().text();
            var current_page = $(this).val();
            current_page = $.trim(current_page);
            if (isNaN(current_page)) {
                current_page = 1;
            } else if (current_page) {
                if (parseInt(current_page) > parseInt(max_current_value)) {
                    current_page = max_current_value;
                } else if (parseInt(current_page) < 1) {
                    current_page = 1;
                }
            } else {
                current_page = 1;
            }
            settings._obj.find("#_current_page").val(current_page);
            paginationAjax(settings);
        });
    };
    /**
     * 数据的加载实现
     * @param {type} settings
     * @param {type} list
     * @returns {undefined}
     */
    var paginationAchieve = function(settings, list) {
        var options = new Array();
        var buffer = new StringBuffer();
        var $table = $("#" + settings.id);
        var trs = $table.find("tr:first");
        var tds = trs.children();
        $(tds).each(function() {
            var option = $(this).attr("data-options");
            if (option) {
                options.push(eval("({" + option + "})"));
            } else {
                options.push(null);
            }
        });
        if (list.length) {
            $(list).each(function(i, item) {
                buffer.append("<tr>");
                $(options).each(function(j, obj) {
                    if (obj) {
                        var align = obj.align === undefined ? "left" : obj.align;
                        var field = htmlCoding(item[obj.field]);
                        var formatter = obj.formatter;
                        var type = obj.type;
                        if (formatter) {
                            field = formatter(item);
                        }
                        buffer.append("<td style = \"text-align:" + align + "\">");
                        if (type) {
                            buffer.append("<input type = \"" + type + "\"   value = \"" + field + "\" name = \"" + obj.field + "\">");
                        } else {
                            buffer.append(field);
                        }
                    } else {
                        buffer.append("<td>");
                    }
                    buffer.append("</td>");
                });
                buffer.append("</tr>");
            });
        } else {
            buffer.append("<tr><td style = \"text-align: center;\" colspan = \"" + options.length + "\">无相关信息</td></tr>");
        }
        $table.find("tr:gt(0)").remove();
        $table.append(buffer.toString());
    };

    function htmlCoding(input) {
        if (input) {
            if ("string" === typeof (input)) {
                input = input.replace(/</g, "&lt;");
                input = input.replace(/>/g, "&gt;");
                input = input.replace(/'/g, "&#039;");
                input = input.replace(/\"/g, "&quot;");
                input = input.replace(/ /g, "&nbsp;");
            }
        } else {
            input = "";
        }
        return input;
    }


    function StringBuffer() {
        this._strings_ = new Array();
    }

    StringBuffer.prototype.append = function(str) {
        this._strings_.push(str);
    };
    StringBuffer.prototype.toString = function() {
        return this._strings_.join("");
    };
    $.fn.pagination.defaults = {
        id: null, //数据展示表格
        url: null, // 地址
        param: null, // 参数
        bean: null, //PaginationBean属性
        success: null, //ajax加载成功
        error: null, //ajax加载错误
        type: "post", //方式
        async: true, //同步
        achieve: false, //数据的加载实现
        dataType: "json", // 数据总条数
        currentPage: 1, // 当前页数
        pageSize: 10                                         // 每页显示大小 
    };
})(jQuery);

